<?php
/**
 * Created by PhpStorm.
 * Doctor: yzapple
 * Date: 2018/1/17
 * Time: 上午9:21
 */
namespace app\common\library;

use app\common\model\Doctor;
use think\Cookie;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;
use think\Validate;

/**
 * DoctorAuth类
 */
class DoctorAuth implements \JsonSerializable, \ArrayAccess
{

    const ERR_ACCOUNT_IS_INCORRECT = '账号不正确';
    const ERR_ACCOUNT_NOT_EXIST = '账号不存在';
    const ERR_PHONE_IS_INCORRECT = '账号不正确';
    const ERR_PASSWORD_IS_INCORRECT = '密码不正确';
    const ERR_PASSWORD_IS_INCORRECT_LENGTH = '密码6-20位';

    const ERR_doctorNAME_OR_PASSWORD_IS_INCORRECT = '账号或密码不正确';
    const ERR_PHONE_ALREADY_EXIST = '账号已存在';
    const ERR_ACCOUNT_IS_LOCKED = '账号禁用';
    const ERR_ACCOUNT_IS_DELETED = '账号已被删除';
    const ERR_PASSWORD_IS_NULL = '密码不能为空';

    const ERR_YOU_ARE_NOT_LOGGED_IN = '您还没有登录';
    const ERR_ACCOUNT_ALREADY_LOGGED_IN_AT_ANOTHER_PLACE = '已在另一端登录';

    protected static $instance = null;
    private $_error = '';
    private $_logined = FALSE;
    private $doctor = NULL;
    private $keeptime = 0;
    private $requestUri = '';

    public function __construct()
    {
        $this->doctor = new Doctor;
    }

    /**
     * 初始化
     * @param array $options 参数
     * @return DoctorAuth
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }

        return self::$instance;
    }

    /**
     *
     * @return doctor
     */
    public function getModel()
    {
        return $this->doctor;
    }

    public function __get($name)
    {
        return $this->check() ? $this->doctor->$name : NULL;
    }

    public function __call($name, $arguments)
    {
        return call_user_func_array([$this->doctor, $name], $arguments);
    }

    /**
     * 用户登录
     *
     * @param string $account 账号,用户名、邮箱、手机号
     * @param string $password 密码
     * @param int $keeptime 有效时长,默认为浏览器关闭
     * @return array
     */
    public function login($account, $password, $keeptime = 0, $sync = TRUE)
    {
        $field = 'dc.username';
        $doctor = $this->doctor->alias('dc')->field('dc.*,doctor_department.department')->join('doctor_department ','doctor_department.id=dc.depart_id')->where([$field => $account])->find();
//var_dump($doctor['department']);
        if ($doctor) {
            if ($doctor->is_deleted == '2') {
                $this->setError(self::ERR_ACCOUNT_IS_LOCKED);
                return FALSE;
            }
            if ($doctor->is_deleted == '3') {
                $this->setError(self::ERR_ACCOUNT_IS_DELETED);
                return FALSE;
            }

            if ($doctor->password != $this->getMd5Password($password)) {
                $this->setError(self::ERR_PASSWORD_IS_INCORRECT);
                return FALSE;
            }

            $this->doctor = $doctor;

            // 设置登录有效时长
            $this->keeptime($keeptime);
            $this->syncLogin($sync);
            return $doctor;
        } else {
            $this->setError(self::ERR_ACCOUNT_NOT_EXIST);
            return FALSE;
        }
    }

    /**
     * 注销登录退出
     * @return bool
     */
    public function logout($token = NULL)
    {
        //设置登录标识
        $this->_logined = FALSE;
        Session::delete('doc_uid');

        return TRUE;
    }


    /**
     * 初始化
     *
     * @param int $doctor_id 会员ID,默认从Cookie中取
     * @param string $token 会员Token,默认从Cookie中取
     *
     * @return boolean
     */
    public function init($doctor_id = NULL, $token = NULL)
    {
        $doctor_id = $doctor_id ? $doctor_id : Session::get('doc_uid');
        $doctor_id = intval($doctor_id);
        if ($doctor_id > 0) {
            if ($this->_error)
                return FALSE;
            $doctor = $this->alias('dc')->field('dc.*,doctor_department.department')->join('doctor_department ','doctor_department.id=dc.depart_id')->where(['dc.id' => $doctor_id])->find();
;
            if (!$doctor) {
                $this->setError(self::ERR_ACCOUNT_NOT_EXIST);
                return FALSE;
            }
            if ($doctor['is_deleted'] == 2) {
                $this->setError(self::ERR_ACCOUNT_IS_LOCKED);
                return FALSE;
            }
            if ($doctor['is_deleted'] == 3) {
                $this->setError(self::ERR_ACCOUNT_IS_DELETED);
                return FALSE;
            }

            $this->doctor = $doctor;
            $this->_logined = TRUE;
            return TRUE;
        } else {

            $this->setError(self::ERR_YOU_ARE_NOT_LOGGED_IN);
            return FALSE;
        }
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function check()
    {
        return $this->_logined;
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function isLogin()
    {
        return $this->check();
    }

    /**
     * 获取当前请求的URI
     * @return string
     */
    public function getRequestUri()
    {
        return $this->requestUri;
    }

    /**
     * 设置当前请求的URI
     * @param string $uri
     */
    public function setRequestUri($uri)
    {
        $this->requestUri = $uri;
    }


    /**
     * 直接登录账号
     * @param int $doctor_id
     * @param boolean $sync
     * @return boolean
     */
    public function direct($doctor_id, $sync = TRUE)
    {
        $this->doctor = $this->doctor->get($doctor_id);
        if ($this->doctor) {
            $this->syncLogin($sync);
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * 获取密码加密方式
     * @param string $password
     * @return string
     */
    public function getMd5Password($password)
    {
        return md5($password);
    }


    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return FALSE;
        }
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return TRUE;
        }

        // 没找到匹配
        return FALSE;
    }

    /**
     * 同步登录信息
     * @param int $sync
     * @return boolean
     */
    protected function syncLogin($sync = TRUE)
    {

        //增加登录次数和设置最后登录时间
      $this->doctor->allowField(true)->save([
            'logintime' => time(),
        ]);

        // 写入登录Cookies和Token
        $this->writeStatus();
        return TRUE;
    }

    /**
     * 写入登录态和Cookie
     *
     * @param int $keeptime
     */
    protected function writeStatus()
    {
        //设置登录标识
        $this->_logined = TRUE;

        Session::set('doc_uid', $this->doctor->id);
        //加密安全字符
        $this->setError('');
    }

    /**
     * 设置会话有效时间
     * @param int $keeptime 默认为永久
     */
    public function keeptime($keeptime = 0)
    {
        $this->keeptime = $keeptime;
    }


    /**
     * 设置错误信息
     *
     * @param $error
     */
    public function setError($error)
    {
        $this->_error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->_error;
    }

    public function __toString()
    {
        return $this->doctor->toJson();
    }

    // JsonSerializable
    public function jsonSerialize()
    {
        return $this->doctor->toArray();
    }

    // ArrayAccess
    public function offsetSet($name, $value)
    {
        $this->doctor->setAttr($name, $value);
    }

    public function offsetExists($name)
    {
        return $this->doctor->__isset($name);
    }

    public function offsetUnset($name)
    {
        $this->doctor->__unset($name);
    }

    public function offsetGet($name)
    {
        return $this->doctor->getAttr($name);
    }

}